<script lang="ts" setup>
import { FormInstance, FormRules } from 'element-plus'
import { Menu, addMenuApi, updateMenuApi } from '/@/api/auth/menu'
import { CreateEditDialog, EditDialogType } from '/@/components/QsEditDialog'
import { baseMessage } from '/@/utils/message'

const formRef = ref<FormInstance>()
const updateId = ref<number>()
const parentTitle = ref<string>()
const emit = defineEmits(['refresh'])
const form = ref<Omit<Menu, 'id' | 'component' | 'path' | 'name'>>({
  sort: 0,
  type: 2,
  parentId: 0,
  status: 1,
  permission: '',
  meta: {
    title: '',
    guard: [],
  },
  menuName: '',
  level: 1,
  redirect: '',
})
const confirm = async (type: EditDialogType) => {
  await formRef.value?.validate().then(async () => {
    if (type == EditDialogType.ADD || type == EditDialogType.SUBLEVEL) {
      const permissionArray: string[] = []
      const titleArray: string[] = []
      if (!form.value.permission) return
      if (form.value.permission.indexOf(',') > -1) {
        permissionArray.push(...form.value.permission.split(','))
        titleArray.push(...(form.value.meta.title as string).split(','))
      } else {
        permissionArray.push(form.value.permission)
      }
      const promiseArray: Promise<BaseResponseWithData<Menu>>[] = []
      permissionArray.forEach(async (permission, index) => {
        promiseArray.push(
          addMenuApi({
            sort: form.value.sort,
            type: form.value.type,
            parentId: form.value.parentId,
            status: form.value.status,
            permission,
            meta: {
              title: titleArray.length > 0 ? titleArray[index] ?? titleArray[0] : form.value.meta.title,
            },
          })
        )
      })
      const result = await Promise.all(promiseArray)
      result.forEach((item) => {
        if (item.result) {
          baseMessage('添加成功')
        }
      })
    } else {
      if (!updateId.value) return
      const { result } = await updateMenuApi(updateId.value, form.value)
      if (result[0]) {
        baseMessage('修改成功')
      }
    }
  })
}

const { open, Dialog } = new CreateEditDialog<Menu>({
  width: '800px',
  title: '权限',
  confirm: confirm,
  closeCallback: () => {
    formRef.value?.resetFields()
    parentTitle.value = undefined
    form.value.parentId = 0
  },
  openCallBack: ({ data, type }) => {
    if (data) {
      if (type == EditDialogType.EDIT || type == EditDialogType.COPY) {
        updateId.value = data.id
        form.value = data
      } else if (type == EditDialogType.SUBLEVEL) {
        form.value.parentId = data.id
        parentTitle.value = data.meta.title
      }
    }
  },
  refresh: () => emit('refresh'),
})
export type ShowEditDialog = typeof open

const rules: FormRules = {
  // name: [{ required: true, message: '请输入菜单名称', trigger: 'blur' }],
  name: [
    { required: true, message: '请输入菜单名称', trigger: 'blur' },
    {
      pattern: /^[A-Z]/,
      message: '必须大写字母开头',
      trigger: 'change',
    },
  ],
  path: [{ required: true, message: '请输入路径', trigger: 'blur' }],
  component: [{ required: true, message: '请输入组件路径', trigger: 'blur' }],
  'meta.title': [{ required: true, message: '请输入标题', trigger: 'blur' }],
  sort: [{ required: true, message: '请输入排序', trigger: 'blur' }],
}
defineExpose({
  open,
})
</script>

<template>
  <Dialog>
    <el-form ref="formRef" label-width="120px" :model="form" :rules="rules">
      <ElRow :gutter="40">
        <el-col :span="11">
          <el-form-item label="父级" prop="parentId">
            <el-input v-model="parentTitle" disabled />
          </el-form-item>
        </el-col>
        <el-col :span="11">
          <el-form-item label="标题" prop="meta.title">
            <el-input v-model="form.meta.title" placeholder="请输入标题" />
          </el-form-item>
        </el-col>
        <el-col :span="11">
          <el-form-item label="权限" prop="permission">
            <el-input v-model="form.permission" placeholder="请输入权限" />
          </el-form-item>
        </el-col>
        <el-col :span="11">
          <el-form-item label="排序" prop="sort">
            <el-input v-model="form.sort" placeholder="请输入排序" type="number" />
          </el-form-item>
        </el-col>
      </ElRow>
    </el-form>
  </Dialog>
</template>

<style lang="scss" scoped></style>
